import re
from metagpt.actions import Action
from metagpt.logs import logger
from llama_index.core.query_engine import RetrieverQueryEngine
import time
from datetime import datetime
import requests

class RetrieveTutorial(Action):
    name: str = "RetrieveTutorial"
    
    async def run(self, filenames: str, query_engine: RetrieverQueryEngine):
        
        
        filename = filenames.split("\n")[0]
        questions = filenames.strip().split("\n")[1:]
        
        questions_filtered = [x for x in questions if x != ""]
        
        
        answers = []
        for question in questions_filtered:
            answer = query_engine.query(question).response
            answers.append(answer)

        final_rsp = "\n".join(answers)

        timestamp = time.time()
        # 将秒数转换为日期和时间
        dt_object = datetime.fromtimestamp(timestamp)
        # 将日期和时间转换为字符串
        human_readable_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
        data = {"time": human_readable_time,"compare":timestamp,"sender":"rag_agent","receiver":"code_enhancer","content":final_rsp}
        response = requests.post("http://localhost:5400/post_msg",json=data)
        response_data = response.json()
        print(response_data)

        return filename + "\n" + "\n".join(answers)

class RetrieveTutorialAfterCorrect(RetrieveTutorial):
    name: str = "RetrieveTutorialAfterCorrect"
